package com.whimscrew.area.controller;

import com.whimscrew.area.model.Area;
import com.whimscrew.area.model.AreaStoreDTO;
import com.whimscrew.area.service.StoreService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

@RestController
@RequestMapping("v1/area")
public class AreaStoreController {


    @Autowired
    StoreService storeService;

    @Autowired
    RedisTemplate   redisTemplate;

    /**
     * 区域对应的商店列表
     * @param areaCode
     * @return
     */
    @GetMapping("{areaCode}/stores")
    public AreaStoreDTO  stores(@PathVariable String  areaCode){
        AreaStoreDTO dto = new AreaStoreDTO();
        dto.setAreaCode(areaCode);
        dto.setStores(storeService.storeList(areaCode));
        redisTemplate.opsForHash().put("areaStore", areaCode, dto);
        return dto;
    }

    /**
     * 获取已缓存的数据
     */
    @GetMapping("cache-stores")
    public Map cacheStores( ){
        return  redisTemplate.opsForHash().entries("areaStore");
    }


    /**
     * 区域列表1~10
     */
    @GetMapping("list")
    public List<Area> list(  ){
        List<Area> resultList = new ArrayList<>(10);
        IntStream.rangeClosed(1,10).forEach(i->{
            String name = RandomStringUtils.randomAlphabetic(4);
            Area area = new Area().setAreaCode(String.valueOf(i)).setAreaName(name);
            resultList.add(area);
        });
        return resultList;
    }

}
